import { v4 as UId4 } from 'uuid'
import dayjs from 'dayjs'
import { cloneDeep, find, isDate, isNaN, round } from 'lodash'
import mime from 'mime'
// import downloadjs from 'downloadjs'

export const createUnionId = () => UId4()

// 获取url链接资源类型
export const getUrlType = url => {
  // 兼容jfif图片格式
  if (/.jfif$/.test(url)) {
    return 'image/jfif'
  } else {
    return mime.getType(url)
  }
}

// 下载
// export const downloadjsHandle = (url, type) => { return downloadjs(url, type) }

export const createUniqueString = () => {
  return UId4()
}

export const deepClone = (obj) => cloneDeep(obj)

/** 格式化时间 */
export const formatTime = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  if (!date) {
    return ''
  }
  if (!isDate(date) && !isNaN(date * 1)) {
    date = date.toString().length < 13 ? date * 1000 : date * 1
  }
  return dayjs(date).format(format)
}
// 返回当天最后一秒的时间
export const formatEndtime = (date, format = 'YYYY-MM-DD HH:mm:ss') => {
  return date ? dayjs(date).add(1, 'day').subtract(1, 'second').format(format) : ''
}

/**
 * 获取时长
 * @param {*} num 秒
 * @param {*} type  来自 dayjs
 * @returns 1 h 30 min 1 s
 */
export function formatDuration(num, type = 'seconds') {
  const time = dayjs.duration(num, type)
  const timeMap = {
    minutes: 'min',
    hours: 'h',
    months: 'm',
    years: 'y',
    seconds: 's',
    days: 'd'
  }
  const res = []
  Object.keys(time.$d).forEach((key) => {
    time.$d[key] && (res.push(...[time.$d[key], timeMap[key]]))
  })
  return res.length ? res.join(' ') : 0
}

/**
 * 根据数组查找包含 key: keyValue的元素对象
 * @param {*} objArr [{value: 1, label: 'a'}]
 * @param {*} key "value"
 * @param {*} keyValue 1
 * @returns {value: 1, label: 'a'}
 */
export const findArrItemFromkey = (objArr, key, keyValue) => {
  return find(objArr, [key, keyValue])
}
/**
 * 将数组转换成，map
 * @param {*} objArr [{value: 1, label: 'a'}, {value: 2, label: 'b'}]
 * @param {*} key "value"
 * @param {*} valueKey "label"
 * @returns Map -> {1: 'a', 2: 'b'}
 */
export const mapFormObjArr = (objArr, key, valueKey) => {
  return new Map(objArr.map(it => [it[key], it[valueKey]]))
}

// 转成千位并取小数点后三位
export const toFixedK = (value) => {
  return (Number(value) / 1000).toFixed(3)
}

// 将秒转化为时分秒
export const formatSeconds = (duration) => {
  if (!duration) return '-'
  const seconds = parseInt(duration % 60)
  const mins = parseInt(duration % 3600 / 60)
  const hours = parseInt(duration / 3600)
  return `${hours}h ${mins}min ${seconds}s`
}

// 准驼峰
export const toHump = (name) => {
  return name.replace(/\_(\w)/g, function(all, letter) {
    return letter.toUpperCase()
  })
}

// 转小时
export const toHour = (value) => {
  return (Number(value) / 3600).toFixed(3)
}

// 百分比
export const toFixedPer = (value) => {
  return (Number(value) * 100).toFixed(2)
}
// blob转字符串
export function transformBlob(blob) {
  return new Promise((reslove) => {
    var reader = new FileReader()
    reader.readAsText(blob, 'utf-8')
    reader.onload = function(e) {
      reslove(reader.result)
    }
  })
}

// 判断值是否为undefined
export function isUndefined(value) {
  return value === undefined
}

// 获取字典的label
export function getDictionaryLabel(code, list) {
  if (!code) return ''
  const item = list?.find(it => it.value === code)
  return item ? item.label : code
}

/**
 *
 * @param {*} user 申请人/创建人/更新人
 */
export function formatUserName(user) {
  if (!user || +user === -1 || user === 'null') {
    return '未找到邮箱'
  }
  return user
}

// 获取url是否可预览
export const isPreviewType = (url) => {
  const type = getUrlType(url)
  return type ? type.indexOf('pdf') !== -1 || type.indexOf('image') !== -1 : type
}

// 获取url是否sf链接
export const isSfType = (url) => {
  return url.indexOf('salesforce') !== -1
}

// 是pdf还是img
export const isTypePdfOrImg = (url) => {
  const type = getUrlType(url)
  if (type.indexOf('pdf') !== -1) {
    return 'pdf'
  }
  if (type.indexOf('image') !== -1) {
    return 'image'
  }
}

// 字典匹配文/翻译
export const getStatusText = (status = '', statusOptions = []) => {
  const item = statusOptions.filter((item) => item.value === String(status))
  return item.length > 0 ? item[0].label : ''
}

// 金额保留两位小数后四舍五入
export const toFixedHandle = (num = 0) => {
  return round(num, 2).toFixed(2)
}

/**
 *
 * @param {*} money 金额
 * @param {*} format 小数点个数
 */
export function formatMoneyAmount(money, format = 2) {
  if (!money) {
    return '0.00'
  }
  return round(money, 2).toFixed(format)
}

// 表格中数组转换成字符串中间加,
export const formatArrayToStr = (array, separator = ',') => {
  if (!array || Object.prototype.toString.call(array) !== '[object Array]') {
    return '-'
  }
  return array.join(separator)
}

// 是否有权限
export const hasPermission = (permissionList, permission) => permissionList.includes(permission)

// 当前审批人生成邮箱和审批人
export const geneateAccountOrNameList = (currentApprovalList = [], isQuestionType = false) => {
  const accountList = []
  const nameList = []
  const approveUserTypeList = []
  currentApprovalList?.forEach(it => {
    if (it.nodeHandleSystem === 'finance') {
      if (it.approveUserType === 'question') {
        approveUserTypeList.push(it.approveUserEmail)
      } else {
        accountList.push(it.approveUserEmail)
      }
    }
    nameList.push(it.approveUserName)
  })
  if (isQuestionType) {
    return { accountList, nameList, approveUserTypeList }
  } else {
    return { accountList, nameList }
  }
}
